import logging, asyncio
from telegram import Update
from telegram.constants import ParseMode  # v20.0+ 版本
from telegram.ext import Application, CommandHandler, MessageHandler, filters, CallbackContext
from buttonMsg_daohang import daohang_text,daohang_markup,start_reply_markup,keyword_muban_dict

class TelegramBot:
    def __init__(self, token: str):
        self.token = token
        self.message_tracker = {}  # 存储待删除的消息 {chat_id: [message_id1, message_id2]}
        self.application = Application.builder().token(token).build()
        
        # 配置日志
        logging.basicConfig(level=logging.WARNING)
        self.logger = logging.getLogger(__name__)
        self.logger.setLevel(logging.DEBUG)  # Allow all messages through to handlers

        # 清除可能存在的旧handler
        for handler in self.logger.handlers[:]:
            self.logger.removeHandler(handler)

        # 创建文件handler，只记录WARNING及以上级别
        file_handler = logging.FileHandler('bot.log', encoding='utf-8')
        file_handler.setLevel(logging.WARNING)
        file_handler.setFormatter(logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s'))

        # 创建控制台handler，记录INFO及以上级别
        console_handler = logging.StreamHandler()
        console_handler.setLevel(logging.INFO)
        console_handler.setFormatter(logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s'))

        # 添加handler
        self.logger.addHandler(file_handler)
        self.logger.addHandler(console_handler)

    # 添加错误日志记录
    def error_handler(self, update: object, context: CallbackContext) -> None:
        try:
            self.logger.error('处理更新时发生错误', exc_info=context.error)
        except UnicodeEncodeError:
            self.logger.error('处理更新时发生错误 (编码问题)', exc_info=context.error)

    # 删除消息的函数
    async def deleteMsg(self, chat_id: int) -> None:
        """删除超过60秒的旧消息"""
        if chat_id not in self.message_tracker:
            return
            
        current_time = asyncio.get_event_loop().time()
        messages_to_keep = []
        
        for msg_id in self.message_tracker[chat_id]:
            try:
                # 获取消息时间并检查是否超过60秒
                # 注意: 实际实现需要获取消息时间戳，这里简化处理
                if current_time - msg_id['timestamp'] > 60:
                    await self.application.bot.delete_message(
                        chat_id=chat_id,
                        message_id=msg_id['id']
                    )
                else:
                    messages_to_keep.append(msg_id)
            except Exception as e:
                self.logger.warning(f"删除消息失败: {e}")
                
        self.message_tracker[chat_id] = messages_to_keep

    async def handle_message(self, update: Update, context: CallbackContext) -> None:
        if update.effective_chat.type != 'group' and update.effective_chat.type != 'supergroup':
            text = update.message.text
            if text in keyword_muban_dict:
                await update.message.reply_text(keyword_muban_dict[text])  #根据发送信息，响应对应内容

            return  # 跳过非群组消息
        
        #群组消息
        text = update.message.text.lower().strip()  # 转为小写方便匹配
        chat_id = update.effective_chat.id    # 获取当前聊天ID（群组或私聊）
        
        # 先清理旧消息
        await self.deleteMsg(chat_id)
        
        # 关键词匹配逻辑（示例：匹配"你好"或"hi"）
        if "导航" == text :
            if chat_id not in self.message_tracker:
                self.message_tracker[chat_id] = []
            #导航这条消息本身也删除
            self.message_tracker[chat_id].append({
                'id': update.message.message_id,
                'timestamp': asyncio.get_event_loop().time()
            })
            #回复  导航
            message = await update.message.reply_text(
                text=daohang_text,
                parse_mode=ParseMode.HTML,
                disable_web_page_preview=True,
                disable_notification=True,
                reply_markup=daohang_markup
            )
            
            self.message_tracker[chat_id].append({
                'id': message.message_id,
                'timestamp': asyncio.get_event_loop().time()
            })
       
    # elif "报告" == text :

    async def start(self, update, context):
        '''
        机器人私聊窗口
        '''
        # 发送消息并附加键盘
        await update.message.reply_text(
            "请选择一个选项:", 
            reply_markup=start_reply_markup
        )
    def run(self) -> None:
        # 注册消息处理器（处理所有文本消息）
        self.application.add_handler(MessageHandler(filters.TEXT & ~filters.COMMAND, self.handle_message))
        
        #机器人底部开始按钮
        self.application.add_handler(CommandHandler("start", self.start))
        
        # 添加错误处理器
        self.application.add_error_handler(self.error_handler)
        
        # 启动机器人
        self.logger.info("机器人启动中...")
        
        try:
            self.application.run_polling()
        except KeyboardInterrupt:
            self.logger.info("接收到终止信号，正在优雅关闭...")
        except Exception as e:
            self.logger.error(f"机器人运行出错: {e}")
        finally:
            self.logger.info("机器人已停止")

def main() -> None:
    bot = TelegramBot("7877298266:AAFDzi1GMg6hsUW9G7vWSHIc5Jdxi4Nl_7s")
    bot.run()

if __name__ == '__main__':
    main()
